<template>
  <view class="content-edit">
    <view class="header">
      <text class="title">{{ isEdit ? '编辑内容' : '新建内容' }}</text>
    </view>

    <view class="form-content">
      <InputField v-model="formData.title" label="标题" :multiline="true" required placeholder="请输入标题" />

      <!-- 内容类型选择器 -->
      <CustomPicker v-model="formData.type" :options="contentStore.contentTypes.slice(1)" label="内容类型" required />

      <!-- 添加内容类型对应的组件 -->
      <TextContent v-if="formData.type === '文字'" v-model="formData.contents" />

      <ImageContent v-if="formData.type === '媒体'" v-model="formData.images" @error="handleUploadError" />

      <LinkContent v-if="formData.type === '链接'" v-model="formData.links" />

      <view>
        <CustomPicker v-model="selectedTagValue" :options="availableTags" label="标签" rangeKey="label" placeholder="选择标签"
          @change="handleTagSelect" required />
        <scroll-view scroll-x class="tags-scroll">
          <view v-for="tag in selectedTags" :key="tag" class="tag-item">
            {{ tag }}
            <text class="delete-tag" @click="removeTag(tag)">×</text>
          </view>
        </scroll-view>
      </view>


      <view class="form-actions">
        <CustomButton text="取消" @click="handleCancel" backgroundColor="#909399" />
        <CustomButton text="保存" @click="handleSubmit" :loading="saving" backgroundColor="#409eff" />
      </view>
    </view>
  </view>
</template>
<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useContentStore } from '@/stores/content'
import { useTagStore } from '@/stores/tags'
import InputField from '@/components/InputField.vue'
import CustomPicker from '@/components/CustomPicker.vue'
import CustomButton from '@/components/CustomButton.vue'

import TextContent from '@/components/content/TextContent.vue'
import ImageContent from '@/components/content/ImageContent.vue'
import LinkContent from '@/components/content/LinkContent.vue'

const contentStore = useContentStore()
const tagStore = useTagStore()
const isEdit = ref(false)
const saving = ref(false)
const selectedTags = ref([])

// 修改初始化逻辑
const typeIndex = ref(0)
// 修改 formData 初始化

// Update formData initialization to include contents array
const formData = ref({
  title: '',
  type: uni.getStorageSync('lastContentType') || '文字',  // 读取上次的类型
  contents: [''],  // Initialize with an empty text content
  images: [],
  links: [],
  items: [],
  tags: []
})

// 添加标签选择值
const selectedTagValue = ref(uni.getStorageSync('lastSelectedTag') || '')

// 修改类型切换方法
const handleTypeChange = (e) => {
  const { value: type, index } = e
  typeIndex.value = index

  const { title, tags } = formData.value
  formData.value = {
    title,
    tags,
    type,
    contents: [''],
    images: [],
    links: []
  }
}

// 修改 availableTags 计算属性
const availableTags = computed(() => {
  // 从 store 获取最新标签列表
  const tags = tagStore.tags || []
  console.log('tagStore.tags:', tags) // 添加调试日志
  return tags.map(tag => ({
    label: tag.name,
    value: tag.id
  }))
})

// 修改标签选择方法
const handleTagSelect = (e) => {
  console.log('handleTagSelect:', e)
  const tagName = e.value
  const selectedTag = tagStore.tags.find(tag => tag.name === tagName)
  if (selectedTag && !selectedTags.value.includes(selectedTag.name)) {
    selectedTags.value.push(selectedTag.name)
    if (!formData.value.tags) {
      formData.value.tags = []
    }
    formData.value.tags.push(selectedTag.id)
  }
  // selectedTagValue.value = '' // 重置选择器的值，以便下次选择
}


// 移除重复的 onMounted
// 修改 onMounted
// Add this with other refs at the top of script setup
const contentId = ref(null)

// 添加 initEditData 函数定义
const initEditData = async () => {
  try {
    const content = await contentStore.fetchContentDetail(contentId.value)
    console.log('获取到的内容详情:', content)

    if (content) {
      // 设置表单数据
      formData.value = {
        title: content.title,
        type: content.type === 'text' ? '文字' : content.type === 'image' ? '媒体' : '链接',
        contents: content.type === 'text' ? content.items : [''],
        images: content.type === 'image' ? content.items : [],
        links: content.type === 'link' ? content.items : [],
        tags: content.tags || []
      }
      console.log('设置后的表单数据:', formData.value)

      // 设置已选标签
      selectedTags.value = content.tags
        .map(tag => {
          const foundTag = tagStore.tags.find(t => t.id === tag.id)
          console.log('匹配标签:', tag.id, foundTag)
          return foundTag?.name
        })
        .filter(Boolean)
      console.log('设置后的已选标签:', selectedTags.value)

      selectedTagValue.value = selectedTags.value[0] || ""
    }
  } catch (error) {
    console.error('获取内容详情失败:', error)
    uni.showToast({
      title: '获取内容详情失败',
      icon: 'none'
    })
  }
}

onLoad(async (options) => {
  console.log('onLoad options:', options)
  await tagStore.fetchTags()
  console.log('tagStore.tags:', tagStore.tags)

  // 如果有缓存的标签，初始化选中状态
  const lastTag = uni.getStorageSync('lastSelectedTag')
  if (lastTag && !options.id) {  // 非编辑模式才使用缓存
    const selectedTag = tagStore.tags.find(tag => tag.name === lastTag)
    if (selectedTag) {
      selectedTagValue.value = lastTag
      selectedTags.value = [lastTag]
      formData.value.tags = [selectedTag.id]
    }
  }

  if (options.id) {
    contentId.value = Number(options.id)
    isEdit.value = true
    await initEditData()
  }
})

// 移除原有的 onMounted 和 defineExpose

// 定义页面生命周期
defineExpose({
  onLoad
})

// 修改 removeTag 方法
const removeTag = (tagName) => {
  const index = selectedTags.value.indexOf(tagName)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
    // 找到对应的标签 id 并移除
    const tag = tagStore.tags.find(t => t.name === tagName)
    if (tag) {
      formData.value.tags = formData.value.tags.filter(id => id !== tag.id)
    }
  }
}


// 修改提交数据的构造
const handleSubmit = async () => {
  if (!formData.value.title) {
    uni.showToast({
      title: '请输入标题',
      icon: 'none'
    })
    return
  }

  const submitData = {
    id: contentId.value, // Use the stored ID
    title: formData.value.title,
    type: formData.value.type,
    items: [],
    tags: formData.value.tags || []
  }

  // 保存当前选择的类型和标签到缓存
  uni.setStorageSync('lastContentType', formData.value.type)
  uni.setStorageSync('lastSelectedTag', selectedTagValue.value)

  // 根据内容类型整理 items 数据
  switch (formData.value.type) {
    case '文字':
      submitData.items = formData.value.contents || []
      submitData.type = 'text'
      break
    case '媒体':
      submitData.items = formData.value.images || []
      submitData.type = 'image'
      break
    case '链接':
      submitData.items = formData.value.links || []
      submitData.type = 'link'
      break
  }

  saving.value = true
  console.log("submitData", submitData)
  try {
    if (isEdit.value) {
      await contentStore.updateContent(submitData)
    } else {
      await contentStore.createContent(submitData)
    }
    uni.navigateBack()
  } catch (error) {
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    })
  } finally {
    saving.value = false
  }
}

const handleCancel = () => {
  uni.navigateBack()
}

const handleUploadError = (error) => {
  uni.showToast({
    title: error,
    icon: 'none'
  })
}
</script>


<style lang="scss" scoped>
.content-edit {
  padding: 32rpx;

  .header {
    margin-bottom: 32rpx;

    .title {
      font-size: 36rpx;
      font-weight: bold;
    }
  }

  .form-content {
    display: flex;
    flex-direction: column;
    gap: 40rpx;

    .tags-scroll {
      white-space: nowrap;
      margin-bottom: 16rpx;
      margin-top: 8rpx;
      padding: 8rpx 0;

      .tag-item {
        display: inline-flex;
        align-items: center;
        padding: 8rpx 16rpx;
        background-color: #ecf5ff;
        color: #409eff;
        border-radius: 6rpx;
        margin-right: 16rpx;
        font-size: 26rpx;

        .delete-tag {
          margin-left: 8rpx;
          font-size: 28rpx;
          line-height: 1;
        }
      }
    }

    .form-actions {
      display: flex;
      justify-content: center;
      gap: 24rpx;
      margin-top: 48rpx;
      padding: 24rpx;
      border-top: 2rpx solid #ebeef5;
    }
  }
}
</style>